package com.dataeco.api.controller;

import com.dataeco.api.entity.User;
import com.dataeco.api.security.JwtAuthenticationResponse;
import com.dataeco.api.service.AuthService;
import com.dataeco.api.service.UserService;
import com.dataeco.api.utils.ExceptionMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;


@RestController
@RequestMapping("/auth")
public class AuthController {
    private final AuthService authService;


    @Value("${jwt.header}")
    private String tokenHeader;

    private final UserService userService;

    @Autowired
    public AuthController(AuthService authService, UserService userService) {
        this.authService = authService;
        this.userService=userService;
    }

    @PostMapping("/access_token")
    public ResponseEntity<?> createAuthenticationToken(
            HttpServletRequest request) throws AuthenticationException {
       String loginName =  request.getParameter("loginName");
        String loginPass = request.getParameter("loginPass");
        User user = this.userService.findByEmail(loginName);
        ExceptionMsg exceptionMsg=new ExceptionMsg();
        if (user==null){
            exceptionMsg.setCode("10000");
            exceptionMsg.setMessage("The email does not exist.");
            return ResponseEntity.ok(exceptionMsg);
        }else {
            String password=user.getPassword();
            if (!loginPass.equalsIgnoreCase(password)){
                exceptionMsg.setCode("10001");
                exceptionMsg.setMessage("The password is not right.");
                return ResponseEntity.ok(exceptionMsg);
            }
            if (user.getLocked()){
                exceptionMsg.setCode("10002");
                exceptionMsg.setMessage("The account is locked.");
                return ResponseEntity.ok(exceptionMsg);
            }
        }
        final String token = authService.accessToken(loginName, loginPass);
        // Return the token
        return ResponseEntity.ok(new JwtAuthenticationResponse(token,"80000"));
    }

    @PostMapping("/refresh_token")
    public ResponseEntity<?> refreshAndGetAuthenticationToken(
            HttpServletRequest request) throws AuthenticationException {
        String token = request.getHeader(tokenHeader);
        String refreshedToken = authService.refreshToken(token);
        if(refreshedToken == null) {
            return ResponseEntity.badRequest().body(null);
        } else {
            return ResponseEntity.ok(new JwtAuthenticationResponse(refreshedToken,"80000"));
        }
    }
}
